<template>
	<div class="recipe_select_panel">
		<div id="search">
			<el-form :inline="true" id="search_form" label-suffix=":">
				<el-form-item label="物品名">
					<el-input class="form_item" placeholder="请输入配方物品名" v-model="searchName" clearable />
				</el-form-item>
				<el-form-item>
					<el-button size="medium" type="primary" @click="handleSearch()" icon="el-icon-search"
						circle></el-button>
				</el-form-item>
			</el-form>
		</div>
		<!-- 配方显示区域 -->
		<div class="recipe_show">
			<div v-for="(item, index) in items" :key="item.id" class="recipe_part" :ref="`recipePart${index}`">
				<div class="item_name">
					<div class="name">{{item.name}}</div>
					<div v-if="item.recipe != item.defaultRecipe" class="tip">(非默认配方)</div>
				</div>
				<recipe-picker v-if="visible[index]" :recipe-id="item.recipe" :item-id="item.id" :index="index"
					@update="handleUpdate" />
			</div>
		</div>
	</div>
</template>
<script>
	import {
		version
	} from 'vue';
	import recipePicker from "@/components/calculation/recipe/RecipePicker.vue";
	export default {
		name: "RecipeSelectPanel",
		components: {
			recipePicker,
		},
		data() {
			return {}
		},
		props: ["initialRecipes"], // 接收父组件传递的已保存配方（替代原 recipes）
		data() {
			return {
				searchName: null,
				items: [], // 格式变为：{ id: number, name: string, defaultRecipe: number, recipe: number }
				recipes: [], // 存储非默认配方列表（格式：{ item: number, recipe: number }）
				itemTypes: [],
				visible: [], // 用于跟踪哪些元素是可见的
				observers: [], // 用于存储观察器实例
			}
		},
		watch: {
			initialRecipes(initialRecipes) {
				this.items.forEach((item) => {
					item.recipe = item.defaultRecipe;
				})
				// 合并父组件传递的已保存配方
				this.recipes = this.initialRecipes || [];
				this.items.forEach(item => {
					const savedRecipe = this.recipes.find(r => r.item === item.id);
					if (savedRecipe) item.recipe = savedRecipe.recipe;
				});
			}
		},
		methods: {
			handleSearch() {
				this.$api.post("/item/cal/list", {
					name: this.searchName
				}).then((res) => {
					const items = res.data.list.map(item => ({
						...item,
						recipe: item.defaultRecipe // 初始化 recipe 为默认值
					}));

					// 合并父组件传递的已保存配方
					this.recipes = this.initialRecipes || [];
					items.forEach(item => {
						const savedRecipe = this.recipes.find(r => r.item === item.id);
						if (savedRecipe) item.recipe = savedRecipe.recipe;
					});

					this.items = items;
					this.$nextTick(this.setupObservers);
				});
			},
			// 更新事件处理方法
			handleUpdate(itemId, recipeId) {
				// 更新本地 recipe 值
				const item = this.items.find(i => i.id === itemId);
				if (item) item.recipe = recipeId;

				// 更新 recipes 列表
				const index = this.recipes.findIndex(r => r.item === itemId);
				if (recipeId === item.defaultRecipe) {
					// 如果是默认配方则移除
					if (index > -1) this.recipes.splice(index, 1);
				} else {
					// 非默认配方则添加/更新
					if (index > -1) {
						this.recipes[index].recipe = recipeId;
					} else {
						this.recipes.push({
							item: itemId,
							recipe: recipeId
						});
					}
				}

				// 通知父组件更新
				this.$emit("update", this.recipes);
			},
			setupObservers() {
				// 清除之前的观察器
				this.observers.forEach(observer => observer.disconnect());
				this.observers = [];

				// 初始化 visible 数组
				this.visible = new Array(this.items.length).fill(false);

				// 为每个 recipe_part 设置观察器
				this.items.forEach((item, index) => {
					const observer = new IntersectionObserver((entries) => {
						entries.forEach(entry => {
							if (entry.isIntersecting) {
								this.$set(this.visible, index, true);
								observer.unobserve(entry.target); // 停止观察已经可见的元素
							}
						});
					}, {
						root: null,
						rootMargin: '0px',
						threshold: 0.1
					});
					const element = this.$refs[`recipePart${index}`][0];
					if (element) {
						observer.observe(element);
						this.observers.push(observer);
					}
				});
			},
			/**
			 * 对整个组件进行更新，用于版本切换时执行
			 */
			handleFactoryRenew() {
				this.handleSearch();
			}
		},
		created() {
			this.handleSearch();
			this.$version.addListener("calRecipe", this.handleRenew);
		},
		destroyed() {
			this.$version.removeListener("calRecipe");
			this.observers.forEach(observer => observer.disconnect());
		}
	}
</script>
<style lang="less" scoped>
	@import url("/src/assets/less/variables.less");

	.recipe_select_panel {
		background: @color-white;
		width: 98%;
		height: 400px;

		#search {
			width: 100%;
			height: 60px;
			padding: 10px;
			// padding-left: 0;
			margin: 0px;
			border-bottom: 1px solid;
			border-bottom-color: @color-border;
			box-sizing: border-box;

			.el-button--primary {
				background: @color-primary;
				border-color: @color-primary;

				&:hover {
					background: darken(@color-primary, 10%);
					border-color: darken(@color-primary, 10%);
				}
			}

			// 保证搜索框向右对齐
			#search_form {
				float: right;

				/deep/ .el-form-item {
					margin-bottom: 0;
				}

				.form_item {
					// width: 140px;
				}
			}
		}

		.recipe_show {
			width: 100%;
			height: calc(100% - 60px);
			overflow-y: scroll;
			display: flex;
			flex-wrap: wrap;
			justify-content: space-around;

			// 优化物品名样式
			.item_name {
				width: 100%;
				padding: 0 8px 8px 8px; // 调整内边距
				margin-bottom: 8px;
				border-bottom: 1px solid @color-border; // 添加分割线
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;

				.name {
					float: left;
					font-size: 14px;
					font-weight: 600;
					line-height: 1.4;
					color: @color-text;

					&::before {
						// 添加装饰性小图标
						content: "•";
						color: @color-primary;
						margin-right: 6px;
					}

				}

				.tip {
					float: right;
					font-size: 12px;
					color: @color-danger;
				}
			}

			// 修改 .recipe_part 的样式
			.recipe_part {
				width: 40%;
				border: 1px solid @color-border;
				border-radius: 8px;
				margin: 8px;
				padding: 12px;
				background: @color-white;
				transition: box-shadow 0.2s ease;
				max-height: 160px;

				&:hover {
					box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
				}
			}
		}
	}
</style>